//
//  ShowViewController.m
//  svqj
//
//  Created by xftt on 14-6-28.
//
//

#import "ShowViewController.h"
#import "NewWebViewController.h"
#import "MD5.h"

@interface ShowViewController ()<UIWebViewDelegate>
{
    BOOL isShow;
    UILabel *_lbTitle;
    UIWebView *_vWeb;
    UIView *_vBg;
    UIView *_vShare;
}

@end

@implementation ShowViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSInteger barheight = 0;
    if([UIDevice currentDevice].systemVersion.floatValue >= 7.0)
    {
        barheight = 20;
    }
    UIView *showView = [[UIView alloc]initWithFrame:CGRectMake(0, barheight, 1024, 748)];
    [self.view addSubview:showView];
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 50)];
    [titleView setBackgroundColor:[UIColor colorWithHexString:@"#343434"]];
    [showView addSubview:titleView];
    
    _lbTitle = [[UILabel alloc]initWithFrame:titleView.frame];
    [_lbTitle setTextColor:[UIColor whiteColor]];
    [_lbTitle setBackgroundColor:[UIColor clearColor]];
    [_lbTitle setTextAlignment:NSTextAlignmentCenter];
    [showView addSubview:_lbTitle];
    
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnBack setFrame:CGRectMake(0, 0, 70, 50)];
    [btnBack setTitle:@"返回" forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(doClose:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:btnBack];
    
    UIButton *btnShow = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnShow setFrame:CGRectMake(954, 0, 70, 50)];
    [btnShow setTitle:@"分享" forState:UIControlStateNormal];
    [btnShow addTarget:self action:@selector(showShare) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:btnShow];
    
    _vWeb = [[UIWebView alloc] initWithFrame:CGRectMake(0, 50, 1024, 698)];
    [_vWeb.scrollView setBounces:NO];
    [_vWeb setClipsToBounds:YES];
    [showView addSubview:_vWeb];
    _vWeb.delegate = self;
    
    
    _vShare = [[UIView alloc]initWithFrame:CGRectMake(834, -70, 190, 70)];
    [_vShare setBackgroundColor:[UIColor colorWithHexString:@"#555555"]];
    [_vWeb addSubview:_vShare];
    
    //微信分享
    UIButton *btnWeixin =  [[UIButton alloc] initWithFrame:CGRectMake(14, 14, 44, 44)];
    [btnWeixin setBackgroundImage:[UIImage imageNamed:@"weixin"] forState:UIControlStateNormal];
    [btnWeixin addTarget:self action:@selector(doShare:) forControlEvents:UIControlEventTouchUpInside];
    [btnWeixin setTag:1];
    [_vShare addSubview:btnWeixin];
    
    //朋友圈分享
    UIButton *btnPengYou =  [[UIButton alloc] initWithFrame:CGRectMake(74, 14, 44, 44)];
    [btnPengYou setBackgroundImage:[UIImage imageNamed:@"pengyou"] forState:UIControlStateNormal];
    [btnPengYou addTarget:self action:@selector(doShare:) forControlEvents:UIControlEventTouchUpInside];
    [btnPengYou setTag:2];
    [_vShare addSubview:btnPengYou];
    
    //    //QQ分享
    //    btnQQ =  [[UIButton alloc] initWithFrame:CGRectMake(122, 103, 44, 44)];
    //    [btnQQ setBackgroundImage:[UIImage imageNamed:@"QQ"] forState:UIControlStateNormal];
    //    [btnQQ addTarget:self action:@selector(doShare:) forControlEvents:UIControlEventTouchUpInside];
    //    [btnQQ setTag:3];
    //    [btnQQ setHidden:YES];
    //    [self addSubview:btnQQ];
    
    //微博分享
    UIButton *btnWeiBo =  [[UIButton alloc] initWithFrame:CGRectMake(132, 14, 44, 44)];
    [btnWeiBo setBackgroundImage:[UIImage imageNamed:@"xinlang"] forState:UIControlStateNormal];
    [btnWeiBo addTarget:self action:@selector(doShare:) forControlEvents:UIControlEventTouchUpInside];
    [btnWeiBo setTag:4];
    [_vShare addSubview:btnWeiBo];
    
    if (_qj != nil) {
        [self setQj:_qj];
    }
}

-(void)showShare
{
    if (!isShow) {
        [UIView animateWithDuration:0.2
                         animations:^{
                             [_vShare setFrameY:0];
                         } completion:^(BOOL finished){
                         }];
    }
    else
    {
        [UIView animateWithDuration:0.2
                         animations:^{
                             [_vShare setFrameY:-70];
                         } completion:^(BOOL finished){
                         }];
    }
    isShow = !isShow;
}

- (void)doShare:(UIButton*)sender
{
    UIImage *imgShare = nil;
    switch (sender.tag) {
        case 1:
        {
            //微信好友
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = _qj.sharetitle;
            message.description = _qj.intro;
            
            imgShare = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_qj.icon]]];
            
            [message setThumbImage:imgShare];
            
            WXWebpageObject *ext = [WXWebpageObject object];
            ext.webpageUrl = _qj.mob;
            
            message.mediaObject = ext;
            
            SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
            req.bText = NO;
            req.message = message;
            req.scene = WXSceneSession;
            
            [WXApi sendReq:req];
            break;
        }
        case 2:
        {
            //微信朋友圈
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = _qj.sharetitle;
            message.description = _qj.intro;
            
            imgShare = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_qj.icon]]];
            
            [message setThumbImage:imgShare];
            
            WXWebpageObject *ext = [WXWebpageObject object];
            ext.webpageUrl = _qj.mob;
            
            message.mediaObject = ext;
            
            SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
            req.bText = NO;
            req.message = message;
            req.scene = WXSceneTimeline;
            
            [WXApi sendReq:req];
            break;
        }
            //        case 3:
            //            //QQ
            //            break;
        case 4:
        {
            //微博
            WBMessageObject *message = [WBMessageObject message];
            WBWebpageObject *webpage = [WBWebpageObject object];
            webpage.objectID = @"identifier1";
            webpage.title = _qj.sharetitle;
            webpage.description = _qj.intro;
            NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
            NSString* imagePath = [NSString stringWithFormat: @"%@/SVQJ/%@/qjicon.png", docPath, _qj.sid];
            UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
            webpage.thumbnailData = UIImageJPEGRepresentation(img, 0.3);
            webpage.webpageUrl = _qj.pc;
            message.mediaObject = webpage;
            WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
            request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                                 @"Other_Info_1": [NSNumber numberWithInt:123],
                                 @"Other_Info_2": @[@"obj1", @"obj2"],
                                 @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
            [WeiboSDK sendRequest:request];
            break;
        }
    }
    [self showShare];
}


-(void)doClose:(UIButton*)sender
{
//    [self dismissViewControllerAnimated:NO completion:nil];
    [_vWeb stopLoading];
    if (_vWeb != nil) {
        [_vWeb setDelegate:nil];
        _vWeb = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setQj:(QuanJing *)qj
{
    _qj = qj;
    NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
    NSString* path = [NSString stringWithFormat: @"%@/SVQJ/%@/index.html", docPath, qj.sid];
    NSString *encodedPath = [path stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSString *urlStr = [NSString stringWithFormat:@"file://%@", encodedPath];
    
    if([qj.k length]>0)
    {
        NSString * mi = [[MD5 md5:qj.k] substringWithRange:NSMakeRange(4, 16)];
        urlStr = [NSString stringWithFormat: @"%@?k=%@", urlStr,mi];
    }
    
    [_lbTitle setText:qj.title];
    [_vWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeOther ||
        navigationType == UIWebViewNavigationTypeLinkClicked)//点击链接
    {
        NSURL *url = [request URL];
        NSString *query = [url query];
        NSLog(@"url %@ \n %@",url, url.absoluteString);
		if (query && [query rangeOfString:@"openwin=1"].location != NSNotFound)
        {
            [self performSelector:@selector(openURLInNewWebView:) withObject:url.absoluteString afterDelay:0.5];
            return NO;
        }
    }
    
	return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)openURLInNewWebView:(NSString *)url
{
    NewWebViewController *new = [[NewWebViewController alloc]initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:new animated:YES];
//    [self presentViewController:new animated:YES completion:nil];
    [new setUrl:url];
}


@end
